<?php 
/*
 module:		报名管理
 create_time:	2022-03-08 16:17:21
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\service\ZhSignUpService;
use app\api\model\ZhSignUp as ZhSignUpModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use app\backend\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use app\backend\model\ZhActivity as ZhActivityModel;
use app\api\model\ZhPayLog as ZhPayLogModel;
use app\api\service\PaymentService;

class ZhSignUp extends Common {


	/**
	* @api {post} /ZhSignUp/index 01、首页数据列表
	* @apiGroup ZhSignUp
	* @apiVersion 1.0.0
	* @apiDescription  首页数据列表

	* @apiHeader {String} Authorization 用户授权token
	* @apiHeaderExample {json} Header-示例:
	* "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"

	* @apiParam (输入参数：) {int}     		[limit] 每页数据条数（默认20）
	* @apiParam (输入参数：) {int}     		[page] 当前页码
	* @apiParam (输入参数：) {int}			[status] 报名状态 已报名|1|success,未报名|0|warning
	* @apiParam (输入参数：) {int}			[activity_status] 活动状态 待参加|1|success,已过期|0|warning,已参加|2|info

	* @apiParam (失败返回参数：) {object}     	array 返回结果集
	* @apiParam (失败返回参数：) {string}     	array.status 返回错误码 201
	* @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
	* @apiParam (成功返回参数：) {string}     	array 返回结果集
	* @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
	* @apiParam (成功返回参数：) {string}     	array.data 返回数据
	* @apiParam (成功返回参数：) {string}     	array.data.list 返回数据列表
	* @apiParam (成功返回参数：) {string}     	array.data.count 返回数据总数
	* @apiSuccessExample {json} 01 成功示例
	* {"status":"200","data":""}
	* @apiErrorExample {json} 02 失败示例
	* {"status":" 201","msg":"查询失败"}
	*/
	function index(){
		if(!$this->request->isGet()){
			throw new ValidateException('请求错误');
		}
        $wxapp_id       = $this->request->get('wxapp_id');
        $uId            = $this->request->uid;
        $activityStatus = $this->request->get('activity_status');
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
        
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
        

		$limit  = $this->request->get('limit', 20, 'intval');
		$page   = $this->request->get('page', 1, 'intval');
  
		$where             = [];
		$where['status']   = 1;
		$where['wxapp_id'] = $wxapp_id;
		$where['u_id']     = $uId;
		
		$field   = 'sign_up_id,activity_id,status,activity_status';
		$orderby = 'sign_up_id desc';
		
		if($activityStatus == 0){
		    $where['activity_status'] = 0;
        }elseif ($activityStatus == 1){
            $where['activity_status'] = 1;
        }elseif ($activityStatus == 2){
            $where['activity_status'] = 2;
        }

		$res = ZhSignUpService::indexList(formatWhere($where),$field,$orderby,$limit,$page);
		foreach ($res['list'] as &$v){
            $ZhActivityData  = ZhActivityModel::where([
                                                    'wxapp_id'   => $wxapp_id,
                                                    'activity_id'=> $v['activity_id']
                                                    ])->find();
            $v['title']      = $ZhActivityData['title'];
            $v['subtitle']   = $ZhActivityData['subtitle'];
            $v['start_time'] = $ZhActivityData['start_time'];
            $v['address']    = $ZhActivityData['address'];
            $v['images']     = $ZhActivityData['images'];
        }
		return $this->ajaxReturn($this->successCode,'返回成功',htmlOutList($res));
	}

	/**
	* @api {post} /ZhSignUp/add 02、添加
	* @apiGroup ZhSignUp
	* @apiVersion 1.0.0
	* @apiDescription  创建数据

	* @apiHeader {String} Authorization 用户授权token
	* @apiHeaderExample {json} Header-示例:
	* "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
	* @apiParam (输入参数：) {string}			activity_id 活动id (必填) 
	* @apiParam (输入参数：) {string}			u_id 用户id (必填) 
	* @apiParam (输入参数：) {int}				status 报名状态 已报名|1|success,未报名|0|warning
	* @apiParam (输入参数：) {string}			sign_up_price 报名金额 
	* @apiParam (输入参数：) {int}				activity_status 活动状态 待参加|1|success,已过期|0|warning,已参加|2|info

	* @apiParam (失败返回参数：) {object}     	array 返回结果集
	* @apiParam (失败返回参数：) {string}     	array.status 返回错误码  201
	* @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
	* @apiParam (成功返回参数：) {string}     	array 返回结果集
	* @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
	* @apiParam (成功返回参数：) {string}     	array.msg 返回成功消息
	* @apiSuccessExample {json} 01 成功示例
	* {"status":"200","data":"操作成功"}
	* @apiErrorExample {json} 02 失败示例
	* {"status":" 201","msg":"操作失败"}
	*/
	function add(){
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->uid;
        $type     = $this->request->post('type','wx','serach_in');
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
        
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
        
		$postField = 'activity_id,sign_up_price,is_charge';
		$data = $this->request->only(explode(',',$postField),'post',null);
  
		if(!$data['activity_id']){
            return $this->ajaxReturn($this->errorCode,'缺少活动id');
        }
        $activityData = ZhActivityModel::where([
                                            'wxapp_id'   => $wxapp_id,
                                            'activity_id'=> $data['activity_id'],
                                            'status'     => 1
                                        ])->find();
        //如果活动有人数限制
        $count = ZhSignUpModel::where([
                                    'wxapp_id'   => $wxapp_id,
                                    'activity_id'=> $data['activity_id'],
                                    'status'     => 1
                                ])->count();
        if($activityData){
            $time = time();
            if($activityData['activity_num'] && $count >= $activityData['activity_num']){
                return $this->ajaxReturn($this->errorCode,'很遗憾，活动人数已满');
            }elseif ($time > $activityData['sign_up_end_time']){
                return $this->ajaxReturn($this->errorCode,'很遗憾，报名已结束');
            }
        }
        
        $zhSignData = ZhSignUpModel::where([
                                            'wxapp_id'   => $wxapp_id,
                                            'activity_id'=> $data['activity_id'],
                                            'u_id'       => $uId,
                                            'status'     => 1
                                    ])->find();
        if($zhSignData){
            return $this->ajaxReturn($this->errorCode,'您已报名，无需重复报名');
        }
        
        $data['u_id']        = $uId;
        $data['wxapp_id']    = $wxapp_id;
        $data['order_sn']    = $uId . '0' . $wxapp_id . time() . rand(100,999) ;
        $data['createtime']  = time();
        if($data['is_charge']){
            //活动收费  付费改报名状态
            $data['sign_up_price']   = $activityData['sign_up_price'];
            $data['status']          = 0;
    
            ZhSignUpService::add($data);
            $zhSignData = ZhSignUpModel::where([
                                        'wxapp_id'   => $wxapp_id,
                                        'activity_id'=> $data['activity_id'],
                                        'u_id'       => $uId,
                                        'status'     => 0
                                    ])->order('sign_up_id DESC')->find();
            
            $zhPayLogData =  ZhPayLogModel::where([
                                            'wxapp_id'   => $zhSignData['wxapp_id'],
                                            'uid'        => $zhSignData['u_id'],
                                            'order_sn'   => $zhSignData['order_sn'],
                                            'activity_id'=> $zhSignData['activity_id']
                                        ])->find();
            if(!$zhPayLogData){
                $arr = [
                    'wxapp_id'     => $zhSignData['wxapp_id'],
                    'uid'          => $zhSignData['u_id'],
                    'order_sn'     => $zhSignData['order_sn'],
                    'price'        => $zhSignData['sign_up_price'],
                    'status'       => 0,
                    'type'         => '活动报名',
                    'activity_id'  => $zhSignData['activity_id'],
                    'sign_up_price'=> $zhSignData['sign_up_price'],
                    'create_time'  => date('Y-m-d H:i:s',time())
                ];
                ZhPayLogModel::insert($arr);
            }
            if($zhSignData){
                try {
                    $notify_url = 'http://' . $_SERVER['HTTP_HOST'] .'/api/ZhSignUp/payResult/wxapp_id/'.$wxapp_id;
                    if($type == 'wx'){
                        $trade_type = 'JSAPI';
                    }elseif ($type == 'app'){
                        $trade_type = 'APP';
                    } elseif ($type == 'H5'){
                        $trade_type = 'MWEB';
                    }elseif ($type == 'H5-wx'){
                        $trade_type = 'JSAPI';
                        $user['openid'] = $user['official_account_openid'];
                    }
                    $js_pay = PaymentService::instance($wxapp_id,$type)->create($user['openid'], $zhSignData['order_sn'], $zhSignData['sign_up_price'], '报名', ['notify_url' => $notify_url],$trade_type);
                    return $this->ajaxReturn($this->successCode, '操作成功', ['order' => $zhSignData['order_sn'], 'paydata' => $js_pay]);
                } catch (\Exception $e) {
                    return $this->ajaxReturn($this->errorCode, $e->getMessage());
                }
            }
            
        }else{
            //活动免费
            $data['sign_up_price']   = '';
            $data['status']          = 1;
            $data['add_time']        = time();
            $data['activity_status'] = 1;
            if($zhSignData && $zhSignData['status'] == 0){
                $res = ZhSignUpModel::where([
                                            'wxapp_id'   => $wxapp_id,
                                            'activity_id'=> $data['activity_id'],
                                            'u_id'       => $uId,
                                            'status'     => 0
                                        ])->update(['status'=> 1]);
            }else{
                $res = ZhSignUpService::add($data);
            }
        }
		return $this->ajaxReturn($this->successCode,'操作成功',$res);
	}

	/**
	* @api {post} /ZhSignUp/delete 03、删除
	* @apiGroup ZhSignUp
	* @apiVersion 1.0.0
	* @apiDescription  删除

	* @apiHeader {String} Authorization 用户授权token
	* @apiHeaderExample {json} Header-示例:
	* "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
	* @apiParam (输入参数：) {string}     		sign_up_ids 主键id 注意后面跟了s 多数据删除

	* @apiParam (失败返回参数：) {object}     	array 返回结果集
	* @apiParam (失败返回参数：) {string}     	array.status 返回错误码 201
	* @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
	* @apiParam (成功返回参数：) {string}     	array 返回结果集
	* @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
	* @apiParam (成功返回参数：) {string}     	array.msg 返回成功消息
	* @apiSuccessExample {json} 01 成功示例
	* {"status":"200","msg":"操作成功"}
	* @apiErrorExample {json} 02 失败示例
	* {"status":"201","msg":"操作失败"}
	*/
	function delete(){
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->uid;
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
        
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
		$idx =  $this->request->post('sign_up_ids', '', 'serach_in');
		if(empty($idx)){
			throw new ValidateException('参数错误');
		}
		$data['sign_up_id'] = explode(',',$idx);
		try{
			ZhSignUpModel::destroy($data,true);
		}catch(\Exception $e){
			abort(config('my.error_log_code'),$e->getMessage());
		}
		return $this->ajaxReturn($this->successCode,'操作成功');
	}

	/**
	* @api {get} /ZhSignUp/view 04、查看详情
	* @apiGroup ZhSignUp
	* @apiVersion 1.0.0
	* @apiDescription  查看详情
	
	* @apiParam (输入参数：) {string}     		sign_up_id 主键ID

	* @apiHeader {String} Authorization 用户授权token
	* @apiHeaderExample {json} Header-示例:
	* "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"

	* @apiParam (失败返回参数：) {object}     	array 返回结果集
	* @apiParam (失败返回参数：) {string}     	array.status 返回错误码 201
	* @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
	* @apiParam (成功返回参数：) {string}     	array 返回结果集
	* @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
	* @apiParam (成功返回参数：) {string}     	array.data 返回数据详情
	* @apiSuccessExample {json} 01 成功示例
	* {"status":"200","data":""}
	* @apiErrorExample {json} 02 失败示例
	* {"status":"201","msg":"没有数据"}
	*/
	function view(){
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      = $this->request->uid;
        $signUpId = $this->request->get('sign_up_id');
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
        
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
		$data = [
		    'sign_up_id'=> $signUpId,
            'wxapp_id'  => $wxapp_id,
            'u_id'      => $uId
        ];
        
		$field = 'sign_up_id,activity_id,status,add_time,sign_up_price,createtime,activity_status';
		$res   = checkData(ZhSignUpModel::field($field)->where($data)->find());
        $activityData     = ZhActivityModel::where([
                                                'wxapp_id'   => $wxapp_id,
                                                'activity_id'=> $res['activity_id']
                                            ])->find();
        $countNum         = ZhSignUpModel::where([
                                                'wxapp_id'=>$wxapp_id,
                                                'activity_id'=> $res['activity_id']
                                            ])->count();
        $res['total_num']  = $activityData['activity_num'];
        $res['count_num']  = $countNum;
        $res['start_time'] = $activityData['start_time'];
        $res['address']    = $activityData['address'];
        $res['coordinate'] = $activityData['coordinate'];
        $res['username']   = $user['real_name'];
        $res['phone']      = $user['phone'];
		return $this->ajaxReturn($this->successCode,'返回成功',$res);
	}

	
	// 支付回调
    public function payResult()
    {
        $wxapp_id = input('wxapp_id');
        trace('进入回调'.$wxapp_id, 'notify_' . date('Y_m_d'));
        $app      = PaymentService::instance($wxapp_id)::getPayApp();
        $response = $app->handlePaidNotify(function ($message, $fail) use($wxapp_id) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            trace($message, 'notify_' . date('Y_m_d'));
            $order = ZhSignUpModel::where(['order_sn' => $message['out_trade_no']])->find();
            if (!$order || $order->status == 1) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    ZhSignUpModel::where(['order_sn' => $message['out_trade_no'],'wxapp_id'=> $wxapp_id ])->update(['status'=>1,'add_time'=>time(),'activity_status'=>1]);
                    ZhPayLogModel::where(['order_sn' => $message['out_trade_no'],'wxapp_id'=>$wxapp_id])->update(['status'=>1,'wx_order_sn'=>$message['transaction_id']]);
                    // 用户支付失败
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
        return $response->send(); // return $response;
    }
    
    
    /**取消报名**/
    public function cancelSignUp(){
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->uid;
        $signUpId = $this->request->post('activity_id');
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
    
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
        $ZhSignData = ZhSignUpModel::where([
                                        'activity_id'=> $signUpId,
                                        'u_id'       => $uId,
                                        'wxapp_id'   => $wxapp_id,
                                        'status'     => 1
                                    ])->find();
        if(!$signUpId || !$ZhSignData){
            return $this->ajaxReturn($this->errorCode,'参数错误');
        }
        $time = time();
        $ZhActivityData = ZhActivityModel::where([
                                                'wxapp_id'   => $wxapp_id,
                                                'activity_id'=> $ZhSignData['activity_id']
                                            ])->find();
        if($time < $ZhActivityData['sign_up_start_time'] || $time > $ZhActivityData['sign_up_end_time']){
            return $this->ajaxReturn($this->errorCode,'取消报名失败');
        }
        
        $refund_sn = $uId . '2' . $wxapp_id . time() . rand(100,999) ;
        if($ZhSignData['is_charge'] == '1'){
            try {
                PaymentService::instance($wxapp_id)->refund($ZhSignData['order_sn'], $refund_sn, $ZhSignData['sign_up_price'], $ZhSignData['sign_up_price']);
                
            } catch (\Exception $e) {
                return $this->ajaxReturn($this->errorCode, $e->getMessage());
            }
        }
        $res = ZhSignUpModel::where([
                                'wxapp_id'   => $wxapp_id,
                                'activity_id'=> $signUpId,
                                'u_id'       => $uId,
                                'status'     => 1
                            ])->update(['status'=>0]);
        
       if($res && $ZhSignData['is_charge'] == '1'){
           ZhPayLogModel::where([
                               'wxapp_id'=> $wxapp_id,
                               'uid'     => $uId,
                               'order_sn'=> $ZhSignData['order_sn']
                           ])->update(['status'=>2]);
       }
        return $this->ajaxReturn($this->successCode,'取消报名成功');
    }
    

}

